capture log close
clear
capture program drop _all
set more off
timer clear 10
timer on 10
set seed 123

**************** 
***  PATHS   ***  
****************
*BCCR: 1 if at Central Bank
global BCCR=1
if $BCCR == 1 {
	global path "Y:/Projects/MNC_Suppliers/Suppliers_Alfaro-Urena_Manelici_Vasquez"
}

if $BCCR == 0 {
	global path "~/Documents/GitHub/Suppliers_Alfaro-Urena_Manelici_Vasquez"
}
cd $path 

*log file
local logfile "${path0}/log_files/7-appendix_d"
set linesize 255
log using `logfile', replace
set linesize 255

/*
RESULTS IN APPENDIX D OF THE PAPER
*/


********************** 
***  INPUT FILES   ***  
**********************
global revec_group ""raw_data/revec_group.dta""
global events_data ""processed_data/events_data.dta""
global transactions ""raw_data/trans_clean_corresp.dta""
global MNCs ""processed_data/MNC_sample.dta""
global analysis_data ""processed_data/analysis_data.dta""
global SL_info ""raw_data/SL_info.dta""
global events_data ""processed_data/events_data.dta""

*full sample vs restricted
global sample1 "if past!=1"
global sample2 "if event!=."
global cluster1 "province#sector_g"
global cluster2 "province#event"
estimates clear 

********************************************************************************
* main program: outline of the full code
********************************************************************************
prog main_code


*Table D1, D2 and D3. These tables are produced by the code new_matching)

*Table D4. Eventually treated		
		global type_ "onlytreated"
		reg_restricted

*Table D5
*Robustness Restricting the Control Group to Only Include Suppliers to Large Firms
		global type_ "bigdom"
		control_suppliers_bigdom

*Table D6
*Robustness Excluding First-time Suppliers Hiring New Managers
		managers
		
*Tables D7, D8, D9 and D10
*Robustness of Baseline Event-Study Results to Sample Restrictions
		robustness_size_sector
		
*Table D11  
*Robustness of Baseline Event-Study Results to Different Sets of Fixed Effects
		tables_diff_fe

*Table D12
*Robustness to Using a Balanced Sample Around Event Time}
		balancing 

end


********************************************************************************
*Table D6
*Robustness Excluding First-time Suppliers Hiring New Managers
********************************************************************************
{
prog managers
display "managers"
quiet{
estimates clear

*first, we need to bring the employer-employee data (same code as in other managers exercise)
capture confirm file temp/ee_full.dta
if _rc!=0 {
do ${path0}/all_codes/Z-MEED.do	
}
*input for later
preserve
use $analysis_data, clear
collapse event, by(ID)
drop if event==.
destring ID, replace
format ID %16.0g
tempfile IDs
save `IDs', replace
restore
use $MNCs, clear
keep ID 
gen MNC_firm=1
destring ID, replace
format ID %16.0g
append using `IDs'
save temp/events.dta, replace

*using output data drom Z-MEED
use temp/ee_full, clear

keep months salar num_ide ID tip_ocupac year  
* MERGING EVENT STUDY FIRMS + MNCS
merge m:1 ID using temp/events.dta
keep if _m==3
drop _m
set seed 123
*saving final file
save temp/managers0, replace

*FIRMS EXPERIENCING A CHANGE IN THE HIGHEST SALARIED WORKER
	quiet events_highest_paid

*FIRMS HIRING NEW WORKER WITH "MANAGER"	OCCUPATION
	quiet events_manager_occupation
	
*FIRMS HIRING A WORKER COMING FROM AN MNC	
	quiet events_workers_from_mnc

*FIRMS HIRING A WORKER COMING FROM A SUPPLIER OF AN MNC	
	quiet events_workers_from_supplier	
}
* TABLES  
	tables_EE_exercise

end

******
*FIRMS EXPERIENCING A CHANGE IN THE HIGHEST SALARIED WORKER
******
prog events_highest_paid

use $analysis_data, clear
destring ID, replace
format ID %16.0g
tempfile events
save `events', replace

use temp/managers0, clear

* RANKING OF WORKERS PER FIRM
sort year ID sala, stable 
by year  ID: gen pos=_N-_n+1
by year  ID: gen num=_N

* IS THE HIGHEST PAID EMPLOYEE A NEW WORKER IN THE FIRM?
bys ID num_iden: egen min_t_trab=min(year)
bys ID: egen entry=min(year)
forvalue i=1/2{
capture drop temp*
gen temp_new_top=(pos==`i' & year==min_t_trab)
replace temp_new_top=0 if year==2006 | year==entry
bys ID year: egen new_top`i'=max(temp_new_top)
capture drop temp*
}
collapse new_top* entry, by(year ID event)
merge m:1 ID year using  `events'
drop _m

* Which firms to exclude because of changes in managers
forvalue i=1/2{
forvalue j=0/1{
capture drop temp*
sort ID, stable
bys ID: gen temp=(year==event-`j' & new_top`i'==1 & entry<event-`j')
bys ID: egen change_top`i'_m`j'=max(temp)
capture drop temp*
}
}
*regressions
global reg_var "y l k m"
*baseline 
global condition1 ""
* change in top 1 employee in the year of the event
global condition2 "& change_top1_m0!=1"
* change in any of the top 2 employeee in the year of the event
global condition3 "& change_top2_m0!=1"
* change in top 1 employee in the year before the event
global condition4 "& change_top1_m1!=1"
* change in any of the top 2 employeee in the year before the event
global condition5 "& change_top2_m1!=1"
global first_condition=1
global n_conditions=5
global type_ "highest_paid"  
reg_ee

end

******
*FIRMS HIRING NEW WORKER WITH "MANAGER"	OCCUPATION
******
prog events_manager_occupation
use $analysis_data, clear
destring ID, replace
format ID %16.0g
tempfile events
save `events', replace

use temp/managers0, clear

*employer is highest paying firm for each person on a given year
sort num_identi year , stable 
gsort num_identi year -sal
by num_identi year: gen pos=_n
keep if pos==1
drop pos

*Occupation is managers
gen occup=floor(tip_ocupac/1000)
gen managers=(occup==1)

* IS A MANAGER EMPLOYEE A NEW WORKER IN THE FIRM?
bys ID num_iden: egen min_t_trab=min(year)
bys ID: egen entry=min(year)
capture drop temp*
gen temp_new_top=(managers==1 & year==min_t_trab)
replace temp_new_top=0 if year==2007 | year==entry
bys ID year: egen new_top=max(temp_new_top)
capture drop temp*

collapse new_top* entry, by(year ID event)
merge m:1 ID year using  `events'
drop _m

* Which firms to exclude because of changes in managers
forvalue j=0/1{
capture drop temp*
bys ID: gen temp=(year==event-`j' & new_top==1 & entry<event-`j')
bys ID: egen change_top_m`j'=max(temp)
capture drop temp*
}

*regressions
global reg_var "y l k m"
*baseline
global condition1 ""
* change in manager employee in the year of the event
global condition2 "& change_top_m0!=1"
* change in top 1 employee in the year before the event
global condition3 "& change_top_m1!=1"
global first_condition=2
global n_conditions=3
global type_ "manager_occupation"  
reg_ee

end

******
*FIRMS HIRING A WORKER COMING FROM AN MNC
******
prog events_workers_from_mnc

use $analysis_data, clear
destring ID, replace
format ID %16.0g
tempfile events
save `events', replace

use temp/managers0, clear

*employer is highest paying firm for each person on a given year
sort num_identi year , stable 
gsort num_identi year -sal
by num_identi year: gen pos=_n
keep if pos==1
drop pos

*Previous firm is an MNC
xtset num_identi year, y
gen MNC_previous=(l.MNC==1)
bys ID year: egen hired_mnc_worker=max(MNC_previous)

collapse hired_mnc_worker, by(year ID)
merge 1:1 ID year using  `events'
drop if _m==1
drop _m

* Which firms to exclude because hiring a worker from MNCs
forvalue j=0/1{
capture drop temp*
bys ID: gen temp=(year==event-`j' & hired_mnc_worker==1)
bys ID: egen firm_hired_mnc_worker_`j'=max(temp)
capture drop temp*
}

*regressions  
global reg_var "y l k m"
* baseline
global condition1 ""
* excluding firms that hired any worker from mnc at event
global condition2 "& firm_hired_mnc_worker_0!=1"
* excluding firms that hired any worker from mnc at event - 1
global condition3 "& firm_hired_mnc_worker_1!=1"
global first_condition=2
global n_conditions=3
global type_ "workers_from_mnc"
reg_ee

end

******
*FIRMS HIRING A WORKER COMING FROM A SUPPLIER OF AN MNC
******
prog events_workers_from_supplier

use $analysis_data, clear
destring ID, replace
format ID %16.0g
tempfile events
save `events', replace

keep if past==1 | event!=.
collapse year, by(ID event)
drop year
replace event=2008 if event==.
tempfile suppliers
save `suppliers', replace

use temp/managers0, clear
*employer is highest paying firm for each person on a given year
sort num_identi year , stable 
gsort num_identi year -sal
by num_identi year: gen pos=_n
keep if pos==1
drop pos

*merging suppliers 
merge m:1 ID using `suppliers'
drop if _m==2
gen supp_MNC=(_m==3 & year>=event)
drop _m

*Previous firm is supplier of MNC
xtset num_identi year, y
gen supp_MNC_previous=(l.supp_MNC==1)
bys ID year: egen hired_supp_mnc_worker=max(supp_MNC_previous)

collapse hired_supp_mnc_worker, by(year ID)
merge 1:1 ID year using  `events'
drop if _m==1
drop _m

* Which firms to exclude because hiring a worker from supp of MNCs
forvalue j=0/1{
capture drop temp*
bys ID: gen temp=(year==event-`j' & hired_supp_mnc_worker==1)
bys ID: egen firm_hired_supp_mnc_worker_`j'=max(temp)
capture drop temp*
}

*regressions  
global reg_var "y l k m"
* baseline
global condition1 ""
* excluding firms that hired any worker from mnc at event
global condition2 "& firm_hired_supp_mnc_worker_0!=1"
* excluding firms that hired any worker from mnc at event - 1
global condition3 "& firm_hired_supp_mnc_worker_1!=1"
global first_condition=2
global n_conditions=3
global type_ "workers_supp_mnc"
reg_ee

end


******
*MANAGERS REGRESSIONS   
******
prog reg_ee

ds D_m4-D_4
global dummies `r(varlist)'

forvalue j=1/1{
forvalue i=$first_condition /$n_conditions {
capture drop red
* REGRESSION
global REG "reghdfe $reg_var D_* ${sample`j'} ${condition`i'} , absorb(year#sector4#province IDs) vce(cluster ${cluster`j'})"
run_reg
if `j'==1{
estadd local Never_Matched "YES"
addfe Never_Matched
}
estimates store ${type_}_`j'_`i'
capture drop red
}
}

end

******
* TABLES  
******
prog tables_EE_exercise

***
*** excluding firms changing highest_paid
***
display "MANAGERS EXERCISE"
#delimit ;
esttab highest_paid* manager_occupation* 
workers_from_mnc* workers_supp_mnc* using 
${path0}/results/4-appendix_d/Supplementary_Table_D6.tex, 
indicate(`r(indicate_fe)' Never_Matched) 
 star(* 0.10 ** 0.05 *** 0.01) varwidth(23) keep(${dummies}) 
 cells("b(fmt(3) star )" "se(par fmt(3))" ) 
stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" 
"Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" 
"\# Fixed Effects" "\# Firms" )) mlabel("Baseline" 
"No $\Delta$ Top 1 Event" "No $\Delta$ Top 2 Event" 
"No $\Delta$ Top 1 Event-1" "No $\Delta$ Top 2 Event-1" 
"No Occ Mng Event" "No Occ Mng Event-1" 
"No MNC Emp Event" "No MNC Emp Event-1"
"No Supp Emp Event" "No Supp Emp Event-1") alignment(c) 
replace noconstant label nodepvar collabels(none) compress type ; 
#delimit cr

end
}

********************************************************************************
*Table D5
*Robustness Restricting the Control Group to Only Include Suppliers to Large Firms
********************************************************************************
{
prog control_suppliers_bigdom

*sample to selling to firms with more than 100 employees 
	quiet sample_bigdom

*restricting control group to suppliers of big dom firms
	quiet suppliers 
	
*regression results 
	global restriction "${type_}"
	reg_restricted
end

********************************************************************************
*selecting big domestic firms
********************************************************************************
prog sample_bigdom
display "selecting Big Dom firms"
*same code from BIG DOMESTIC FIRMS exercise
quiet{
* EXCLUDING FIRMS THAT EXPERIENCED AN EVENT WITH MNC
use $analysis_data, clear
drop if event!=.
keep ID year 
rename ID seller
tempfile events
save `events', replace

*IMPORTING ALL FIRMS
use $analysis_data, clear
bys ID: egen med_workers=median(trabaj_)
keep if med_w>100
distinct ID
bys ID: gen dup=cond(_N==1,0,_n)
drop if dup>1
keep ID   
preserve 
rename ID seller
tempfile as_seller
save `as_seller', replace
restore
rename * b_*
rename b_ID buyer
tempfile as_buyer
save `as_buyer', replace

* TRANSACTIONS
use $transactions, clear
drop if pot==1
** MERGING FIRMS
merge m:1 buyer using `as_buyer'
gen buyer_bigdom=(_m==3)
drop if _m==2
drop _m
merge m:1 seller year using `events'
keep if _m==3
drop _m
*excluding the large buyers when they are sellers
merge m:1 seller using `as_seller'
drop if _m==3
drop _m

}
*saving temp data
save temp/temp_bigdom.dta , replace
end 

********************************************************************************
*suppliers to big dom firms
********************************************************************************
prog suppliers
display "suppliers to ${type_}"

quiet{
*firm level info
use $analysis_data , clear
drop if event!=.
collapse year, by(ID)
drop year
tempfile firm_info
save `firm_info', replace

*using previous data 
use temp/temp_${type_}.dta , clear
keep if buyer_bigdom==1
collapse year ,by(seller)
keep seller
rename seller ID

*merging firm level info
merge 1:1 ID using `firm_info'
gen suppliers_bigdom=(_m==3)
keep if _m==3 
keep ID suppliers_bigdom
tempfile IDs
save `IDs', replace 

*merging back to analysis data 
use $analysis_data , clear
merge m:1 ID using `IDs'
drop _m
keep if event!=. | suppliers_bigdom==1
save temp/temp_${type_}2.dta , replace

* DATA 1: EVENT WITH other firms 
global analysis_data1 ""temp/temp_${type_}2.dta""
*regression	
	global tab_name "${type_}"
}
end

********************************************************************************
*regressions: Table D4 and D5
********************************************************************************
prog reg_restricted
display "regressions for sample ${type_}"
quiet{
estimates clear	
global data_restr_bigdom "$analysis_data1"
global data_restr_onlytreated "$analysis_data"	
global conditional_bigdom "if past!=1"
global conditional_onlytreated "if event!=."
global cluster_bigdom "province#sector_g"
global cluster_onlytreated "province#event"
global name_bigdom "Supplementary_Table_D5"
global name_onlytreated "Supplementary_Table_D4"

global data_restr "${data_restr_${type_}}"
global conditional "${conditional_${type_}}"
global cluster "${cluster_${type_}}"
global name "${name_${type_}}"
	
*using data
use $data_restr , clear
ds D_m4-D_4
global dummies `r(varlist)'
set seed 123
*standard variable names 
capture rename l_not_MNC_event l_not_event
capture rename l_not_MNC_event_2 l_not_event_trans
capture rename l_trans_per_client ave_trans
capture rename l_ave2 ave_trans
capture replace l_clients_non_event=. if l_not_event_trans==.
	
* COLUMN 1: VAR: sales
global REG "reghdfe y  D_*  $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg
estadd local Never_Matched "NO"
estimates store r_1
* COLUMN 2:  VAR: employment
global REG "reghdfe l  D_* $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )" 
global quant "1"
run_reg
estadd local Never_Matched "NO"
estimates store r_2
* COLUMN 3: VAR: m
global REG "reghdfe m  D_*  $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg
estadd local Never_Matched "NO"
estimates store r_3
* COLUMN 4: VAR: CD FUNCTION
global REG "reghdfe y k l m  D_* $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg
estadd local Never_Matched "NO"
capture drop resid
estimates store r_4
* COLUMN 5: REG ACF
capture drop res_ACF
if $BCCR == 1 {
prodest y $conditional , free(l ) state(k) proxy(m) met(lp) acf opt(dfp) reps(500) id(IDs) t(year) fsresidual(res_ACF)
estadd scalar n_firms 
estadd scalar n_obs
estadd scalar n_fe
estadd local Never_Matched "NO"
estimates store p_5
reghdfe res_ACF  D_*  $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster ) resid(resid)
quietly summ res_ACF if resid!=.
scalar mean_dep=r(mean)
scalar sd_dep=r(sd)
estadd scalar mean_dep
estadd scalar sd_dep
estadd scalar n_firms 
estadd scalar n_obs
estadd scalar n_fe
estadd local Never_Matched "NO"
capture drop resid
estimates store r_5
}
* COLUMN 6: sales to others
global REG "reghdfe l_not_event D_* $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg 
estadd local Never_Matched "NO"
estimates store r_6
* COLUMN 7: EVENTUALLY MATCHED, VAR: trans to others
global REG "reghdfe l_not_event_trans D_* $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg 
estadd local Never_Matched "NO"
estimates store r_7

* COLUMN 8: VAR: number of clients
reghdfe l_not_event_trans D_* $conditional , absorb(year#sector4#province IDs) vce(cluster $cluster ) resid(res1)
global REG "reghdfe l_clients_non_event D_* $conditional & res1!=. , absorb(year#sector4#province IDs) vce(cluster $cluster )"
global quant "1"
run_reg 
estadd local Never_Matched "NO"
estimates store r_8

* COLUMN 9: VAR: AVERAGE SALES PER CLIENT (NOT TRIGGERING EVENT)
global REG "reghdfe ave_trans D_* $conditional & res1!=., absorb(year#sector4#province IDs) vce(cluster $cluster )"
run_reg 
estadd local Never_Matched "NO"
capture drop res1
estimates store r_9

* Prepare estimates for -estout-
	estfe r_*, labels(IDs "Firm FE" year#sector4#province "Year-4DSect-Prov FE")
	return list	
}
esttab r_* using ${path0}/results/4-appendix_d/${name}.tex, ///
	indicate(`r(indicate_fe)')  star(* 0.10 ** 0.05 *** 0.01) varwidth(23) keep(${dummies}) cells("b(fmt(3) star )" "se(par fmt(3))" ) ///
	stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))   ///
	mlabel("Total Sales" "Number Workers" "Imput Costs" "CD OLS" "ACF (2015)" "Sales to Others" "Corp. Sales to Others" "Number Other Corp. Buyers" "Ave. Corp. Sales to Others") alignment(c) ///
    replace noconstant label nodepvar collabels(none)   compress	type
	
end
}

********************************************************************************
*Tables D7, D8, D9 and D10
*Robustness of Baseline Event-Study Results to Sample Restrictions
********************************************************************************
{
prog robustness_size_sector
global mnc_filename ""
global size_restriction ""
global sector_restriction ""

*creating data without different restrictions
	quiet size_sector_restrictions

*appendix tables
	robustness_size_sector_tables
	
end

********************************************************************************
*creating data without different restrictions
********************************************************************************
prog size_sector_restrictions

*restrictions domestic firms
	rtr_dom

*restrictions MNCs
	rtr_mnc
	
*all restrictions	
	rtr_all
end
********************************************************************************
*program: restrictions domestic firms
********************************************************************************
prog rtr_dom
display "program: restrictions domestic firms"
global restrictions "_rtr_"
global rtr_size0 ""
global rtr_size1 "domsize_"
global rtr_sect0 ""
global rtr_sect1 "sect_"

forvalue rtrsize = 0/1{
forvalue rtrsect = 0/1{
if `rtrsize'!=0 | `rtrsect'!=0 {

global size_restriction ${rtr_size`rtrsize'}
global sector_restriction ${rtr_sect`rtrsect'}
*running previous codes
quietly do ${path0}/all_codes/1-event_data_creation.do
quietly do ${path0}/all_codes/2-data_preparation.do
robustness_size_sector_reg 
}
}
}

global size_restriction ""
global sector_restriction ""

end

********************************************************************************
*program: restrictions MNCs
********************************************************************************
prog rtr_mnc
display "program: restrictions MNCs"
global restrictions "_rtr_"
global mnc_rtr "mncsize_"

forvalue rtr_mnc_ = 0(25)75 {

global mnc_size_ = `rtr_mnc_'
global mnc_filename = "mncsize`rtr_mnc_'_"
*running previous codes
quietly do ${path0}/all_codes/1-event_data_creation.do
quietly do ${path0}/all_codes/2-data_preparation.do
robustness_size_sector_reg 
}

end

********************************************************************************
*program: all restrictions
********************************************************************************
prog rtr_all
display "program: all restrictions"
global restrictions "_rtr_"

*removing size restrictions for dom firms
global size_restriction "domsize_"

*removing sector restrictions for dom firms
global sector_restriction "sect_"

*removing size restrictions for MNCs
global mnc_rtr "mncsize_"
global mnc_size_ = 0
global mnc_filename = "mncsize0_"

*running previous codes
quietly do ${path0}/all_codes/1-event_data_creation.do
quietly do ${path0}/all_codes/2-data_preparation.do
robustness_size_sector_reg 

end 

********************************************************************************
*robustness_size_sector_reg regressions 
********************************************************************************
prog robustness_size_sector_reg

*  INPUT FILE   
global analysis_data ""processed_data\analysis_data${restrictions}${mnc_filename}${size_restriction}${sector_restriction}.dta""

*loading data	
use $analysis_data , clear

*dummies to show in tables  	
ds D_m4-D_4
global dummies `r(varlist)'
capture drop red

* COLUMN 1: VAR: sales
global REG "reghdfe y  D_* if past!=1 , absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
run_reg
estimates store ${mnc_filename}${size_restriction}${sector_restriction}1

* COLUMN 2:  VAR: employment
global REG "reghdfe l  D_* if past!=1 , absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
global quant "1"
run_reg 
estimates store ${mnc_filename}${size_restriction}${sector_restriction}2

* COLUMN 3: CD FUNCTION
capture drop red
global REG "reghdfe y k l m  D_* if past!=1 , absorb(year#sector4#province IDs) vce(cluster province#sector2)"
run_reg
estimates store ${mnc_filename}${size_restriction}${sector_restriction}3

* COLUMN 4: NEVER MATCHED + EVENTUALLY MATCHED, VAR: trans to to others
global REG "reghdfe l_not_MNC_event_2 D_* if past!=1 , absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
run_reg
estimates store ${mnc_filename}${size_restriction}${sector_restriction}4

* COLUMN 5: NEVER MATCHED + EVENTUALLY MATCHED, VAR: NUMBER OF CLIENTS

reghdfe l_not_MNC_event_2 D_* if past!=1 , absorb(year#sector4#province IDs) ///
vce(cluster province#sector_g) resi(res1)
global REG "reghdfe l_clients_non_event D_* if past!=1 & res1!=., absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
global quant "1"
run_reg
estimates store ${mnc_filename}${size_restriction}${sector_restriction}5

* COLUMN 4: NEVER MATCHED + EVENTUALLY MATCHED, VAR: AVERAGE SALES PER CLIENT (NOT TRIGGERING EVENT)
capture drop red*
global REG "reghdfe l_ave2 D_* if past!=1 & res1!=., absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
run_reg
estimates store ${mnc_filename}${size_restriction}${sector_restriction}6
end

********************************************************************************
* robustness_size_sector_reg tables
********************************************************************************
prog robustness_size_sector_tables

***
* first table: size, then sector restrictions
***
display "Table D8: No Size, No Sector Restrictions for Domestic Firms"
esttab domsize_1 domsize_2 domsize_3 domsize_4 domsize_5 domsize_6 ///
 sect_* ///
using ${path0}/results/4-appendix_d/Supplementary_Table_D7.tex , ///
 star(* 0.10 ** 0.05 *** 0.01) keep(${dummies}) ///
 cells("b(fmt(2) label($\beta$) star )" "se(par fmt(2) label((SE)) )" ) ///
 stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))   ///
 mlabel("Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers" "Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers") ///
 alignment(c) replace noconstant label nodepvar collabels(none) compress type 
 
***
* second table: size + sector (dom) , size + sector (dom + mnc)
***
display "Table D9: No Size and Sector Restrictions for Domestic; + All ''MNCs''"
esttab domsize_sec* mncsize0_dom* ///
using ${path0}/results/4-appendix_d/Supplementary_Table_D8.tex , ///
 star(* 0.10 ** 0.05 *** 0.01) keep(${dummies}) ///
 cells("b(fmt(2) label($\beta$) star )" "se(par fmt(2) label((SE)) )" ) ///
 stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))   ///
 mlabel("Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers" "Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers") ///
 alignment(c) replace noconstant label nodepvar collabels(none) compress type 
 
***
* third table: mnc 0 + mnc 25
***
display "Table D10:  All ''MNCs''; All ``MNCs'' over 25 Median Number of Workers"
esttab mncsize0_1 mncsize0_2 mncsize0_3 mncsize0_4 mncsize0_5 mncsize0_6 ///
 mncsize25_* ///
using ${path0}/results/4-appendix_d/Supplementary_Table_D9.tex , ///
 star(* 0.10 ** 0.05 *** 0.01) keep(${dummies}) ///
 cells("b(fmt(2) label($\beta$) star )" "se(par fmt(2) label((SE)) )" ) ///
 stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))   ///
 mlabel("Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers" "Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers") ///
 alignment(c) replace noconstant label nodepvar collabels(none) compress type 
 
***
* fourth table: mnc 50 + mnc 75
***
display "Table D11: All ``MNCs'' over 50 or 75 Median Number of Workers"
esttab mncsize50_* mncsize75_* ///
using ${path0}/results/4-appendix_d/Supplementary_Table_D10.tex , ///
 star(* 0.10 ** 0.05 *** 0.01) keep(${dummies}) ///
 cells("b(fmt(2) label($\beta$) star )" "se(par fmt(2) label((SE)) )" ) ///
 stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))   ///
 mlabel("Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers" "Total Sales" "Number Workers" "TFP CD OLS" "Corp. Sales Others" "Number Other Buyers" "Av. Sales Other Buyers") ///
 alignment(c) replace noconstant label nodepvar collabels(none) compress type 

end
}

********************************************************************************
*Table D11
*Robustness of Baseline Event-Study Results to Different Sets of Fixed Effects   
********************************************************************************
prog tables_diff_fe
quiet{	
global var1 "y l k m"
global display1 "table CD production function and fixed effects"
global name1 "CD"
global tab_numb1 "D11"
global analysis_data ""processed_data/analysis_data.dta""

*loading data	
use $analysis_data , clear
*dummies to show in tables  	
ds D_m4-D_4
global dummies `r(varlist)'
estimates clear
egen county=group(canton)
}

forvalue v=1/1{
display "Tab${tab_numb`v'}: ${display`v'}"
quiet{
local v=1
*most strict reg
capture drop strict
reghdfe ${var`v'}  D_* if past!=1 , absorb(year#sector4#province IDs) vce(cluster province#sector_g) resid(strict)

* COLUMN 1: NEVER MATCHED + EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_* if past!=1 & strict!=., absorb(year) vce(cluster province#sector_g)"
run_reg
estadd local Never_Matched "YES"
addfe Never_Matched
estimates store m_1

* COLUMN 2: NEVER MATCHED + EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_* if past!=1 & strict!=., absorb(year IDs) vce(cluster province#sector_g)"
run_reg
estadd local Never_Matched "YES"
addfe Never_Matched
estimates store m_2

* COLUMN 3: NEVER MATCHED + EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_* if past!=1 & strict!=., absorb(year#sector4 IDs) vce(cluster province#sector_g)"
run_reg
estadd local Never_Matched "YES"
addfe Never_Matched
estimates store m_3

* COLUMN 4: NEVER MATCHED + EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_* if past!=1 & strict!=., absorb(year#sector4#province IDs) vce(cluster province#sector_g)"
run_reg
estadd local Never_Matched "YES"
addfe Never_Matched
estimates store m_4

* COLUMN 5: NEVER MATCHED + EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_* if past!=1 & strict!=., absorb(year#sector4#county IDs) vce(cluster province#sector_g)"
run_reg
estadd local Never_Matched "YES"
addfe Never_Matched
estimates store m_5

*most strict
capture drop strict
reghdfe y  D_*  if event!=. , absorb(year#sector4#province IDs) vce(cluster province#event) resid(strict)
* COLUMN 6: EVENTUALLY MATCHED
global REG "reghdfe ${var`v'} D_*  if event!=. & strict!=., absorb(year) vce(cluster province#event)"
run_reg
estadd local Never_Matched "NO"
estimates store m_6

* COLUMN 7: EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_*  if event!=. & strict!=., absorb(year IDs) vce(cluster province#event)"
run_reg
estadd local Never_Matched "NO"
estimates store m_7

* COLUMN 8: EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_*  if event!=. & strict!=., absorb(year#sector4 IDs) vce(cluster province#event)"
run_reg
estadd local Never_Matched "NO"
estimates store m_8

* COLUMN 9: EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_*  if event!=. & strict!=., absorb(year#sector4#province IDs) vce(cluster province#event)"
run_reg
estadd local Never_Matched "NO"
estimates store m_9

* COLUMN 10: EVENTUALLY MATCHED
global REG "reghdfe ${var`v'}  D_*  if event!=. & strict!=., absorb(year#sector4#county IDs) vce(cluster province#event)"
run_reg
estadd local Never_Matched "NO"
estimates store m_10

	estfe m_*, labels(IDs "Firm FE" year "Year FE" year#sector4 "Year-4DSect FE" year#sector4#province "Year-4DSect-Prov FE" year#sector4#county "Year-4DSect-County FE")
	return list	
}	
esttab m_* using ${path0}/results/4-appendix_d/Supplementary_Table_${tab_numb`v'}.tex, ///
indicate(`r(indicate_fe)' Never_Matched)  star(* 0.10 ** 0.05 *** 0.01) ///
varwidth(23) keep(${dummies}) ///
cells("b(fmt(3) star )" "se(par fmt(3))" ) ///
stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))  nomtitles alignment(c) ///
replace noconstant label nodepvar collabels(none)  compress type
}
	
end

********************************************************************************
*Table D12
*Robustness to Using a Balanced Sample Around Event Time 
********************************************************************************
prog balancing
quiet{

*loading data	
use $analysis_data , clear
global analysis_data ""processed_data\analysis_data.dta""

*dummies to show in tables  	
ds D_m4-D_4
global dummies `r(varlist)'

estimates clear
capture drop profits
gen profits=log(ingresos-costo_d-salarios/1000)
gen prof=log(profits)
gen sales_to_others=l_not_MNC_event
gen trans_to_others=l_not_MNC_event_2
gen clients=l_clients_non_event
replace clients=. if trans_to_others==.
gen cd_=y
gen tl=y
local outcomes0 "cd"
local controls0 "l k m"

local outcomes1 "tl"
local controls1 "k l m c.l#c.l c.k#c.k c.m#c.m c.k#c.l c.l#c.m c.k#c.m"

local outcomes2 "y l k va sales_to_others l_trans trans_to_others clients"
local controls2 ""
forvalue i=0/2{
foreach v of local outcomes`i'{
global REG "reghdfe `v' `controls`i'' D_* if event!=. & bal==1 , absorb(year#sector4#province IDs) vce(cluster province#sector2)"
if "`v'"=="l" | "`v'"=="clients"{
capture drop dep
global quant=1
}
run_reg
estimates store m_`v'
}
}
estfe  m_* , labels(IDs "Firm FE" year "Year FE" year#sector4#province "Year-4DSect-Prov FE")
return list		
}
display "*Table D15: Robustness to Using a Balanced Sample Around Event Time"
esttab  m_* using ${path0}/results/4-appendix_d/Supplementary_Table_D12.tex, ///
 indicate(`r(indicate_fe)') star(* 0.10 ** 0.05 *** 0.01) keep(${dummies}) ///
 cells("b(fmt(2) label($\beta$) star )" "se(par fmt(2) label((SE)) )" ) ///
 stats(r2_a mean_dep sd_dep n_obs n_fe n_firms , fmt(a2) labels("Adjusted R$^2$" "Mean Dep. Var. (level)" "SD Dep. Var. (level)" "\# Observations" "\# Fixed Effects" "\# Firms" ))  mlabel("TFP CD OLS" "TFP TL OLS" "Total Sales" "Number Workers" "Net Assets" "Value Added" "Sales to Others" "Total Corp Sales" "Corp. Sales to Others" "Number Other Buyers") ///
 alignment(c) replace noconstant label nodepvar collabels(none) compress type	
end


********************************************************************************
*
* additional programs: creating tables and figures
*
********************************************************************************
{
********************************************************************************
*run regression and stores relevant info
********************************************************************************
prog run_reg
capture drop resid
capture drop dep

*regression 
$REG resid(resid) 

* add number of observations 
scalar n_obs=e(N)
estadd scalar n_obs

* add distinct number of firms
distinct IDs if resid!=.
scalar n_firms=r(ndistinct)
estadd scalar n_firms 

* add mean and sd of dependent variable 
global dep_var "`e(depvar)'"
if "$quant" == ""{
*in US dollars
gen dep=exp( $dep_var )/500
}
if "$quant" == "1" {
gen dep=exp( $dep_var )
}
global quant ""
quietly summ dep if resid!=.
scalar mean_dep=r(mean)
scalar sd_dep=r(sd)
estadd scalar mean_dep
estadd scalar sd_dep

*add number of fixed effects 
scalar n_fe=e(df_a_initial)
estadd scalar n_fe

capture drop resid
capture drop dep
end

*  CONSUMER PRICE INDEX  (yearly average) 2013 ==100    
global ipc2005 = 50.99*100/92.88
global ipc2006 = 57.96*100/92.88
global ipc2007 = 63.38*100/92.88
global ipc2008 = 75.43*100/92.88
global ipc2009 = 77.53*100/92.88
global ipc2010 = 81.15*100/92.88
global ipc2011 = 85.57*100/92.88
global ipc2012 = 89.78*100/92.88
global ipc2013 = 92.88*100/92.88
global ipc2014 = 98.99*100/92.88
global ipc2015 = 98.93*100/92.88
global ipc2016 = 100.08*100/92.88
global ipc2017 = 100.77*100/92.88

*  AVERAGE EXCHANGE RATE    
* 1 March of each year: average compra-venta
global tc_2005=477.76578
global tc_2006=511.29055
global tc_2007=516.59063
global tc_2008=526.35683
global tc_2009=573.35611
global tc_2010=525.68364
global tc_2011=505.69
global tc_2012=502.8868
global tc_2013=499.75405
global tc_2014=538.36123
global tc_2015=534.55408
global tc_2016=544.76658
global tc_2017=567.55509
********************************************************************************
* PROGRAM TO GENERATE DIFF IN MEANS
********************************************************************************
capture program drop myttests
program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
	 local varia_program "mu_1 mu_2 n_1 n_2 mu_1_se mu_2_se d d_se d_t d_p"
     tempname `varia_program'
      foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
         mat `n_1' = nullmat(`n_1'), r(N_1)
         mat `n_2' = nullmat(`n_2'), r(N_2)		 
         mat `mu_1_se' = nullmat(`mu_1_se'), r(sd_1)
         mat `mu_2_se' = nullmat(`mu_2_se'), r(sd_2)		 
         mat `d'    = nullmat(`d'   ), r(mu_1)-r(mu_2)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
     }
         foreach mat in `varia_program' {
         mat coln ``mat'' = `varlist'
     }
     tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in `varia_program' {
        eret mat `mat' = ``mat''
    }
 end
 
********************************************************************************
*PROGRAM TO ADD FIXED EFFECTS INDICATOR TO LATEX TABLES           
********************************************************************************
program addfe
    if `"`0'"'=="" local 0 _fe
    tempname b V
    mat `b' = 0
    mat coln `b' = `0'
    mat `b' = e(b), `b'
    mat `V' = e(V)
    mat `V' = (`V', J(rowsof(`V'), 1, 0)) \ (J(1, colsof(`V'), 0), 0)
    erepost b=`b' V=`V', rename
end
 }
******************************************************************************** 
***  EXECUTE THE PROGRAM main   
******************************************************************************** 
main_code 

******************************************************************************** 
***  TIMER
********************************************************************************
timer off 10
*time in seconds
timer list 10
*time in minutes
local time_ =round(`r(t10)'/60)
display "the code takes `time_' minutes in total"

log close
translate `logfile'.smcl `logfile'.txt , replace linesize(255)
erase `logfile'.smcl
